package cn.itcast.web.controller.cargo;


import cn.itcast.domain.cargo.ContractProduct;
import cn.itcast.domain.cargo.ContractProductExample;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {
    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    /*分页查找货物列表*/
    @RequestMapping("/list")
    public String findAll(String contractId,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize){
        //查询生产货物的工厂
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryCriteria = factoryExample.createCriteria();
        factoryCriteria.andCtypeEqualTo("货物").andCompanyIdEqualTo(getLoginUserCompanyId());
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        //根据购销合同ID查询货物列表
        ContractProductExample contractProductExample = new ContractProductExample();
        ContractProductExample.Criteria productCriteria = contractProductExample.createCriteria();
        productCriteria.andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo = contractProductService.findByPage(contractProductExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);

        //3. 购销合同的id
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-list";
    }

    /*
          url:/contractProduct/edit.do
          作用： 保存、修改 货物信息
          参数： contractProduct
         */
    @RequestMapping("/edit")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) throws Exception {
        //货物的创建人
        contractProduct.setCreateBy(getLoginUser().getId());
        //货物的创建人所属的部门
        contractProduct.setCreateDept(getLoginUser().getDeptId());
        //货物的创建人所属的企业id
        contractProduct.setCompanyId(getLoginUserCompanyId());
        //货物的创建人所属的企业名称
        contractProduct.setCompanyName(getLoginUserCompanyName());

        if (!productPhoto.isEmpty()){
            String url = fileUploadUtil.upload(productPhoto);
            contractProduct.setProductImage("http://"+url);
        }

        if (StringUtils.isEmpty(contractProduct.getId())){
            //如果id为空，添加货物信息
            contractProductService.save(contractProduct);
        }else {
            //页面有传id，修改货物信息
            System.out.println("========"+contractProduct);
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();
    }

    /*
          url:/cargo/contractProduct/toUpdate.do?id=0a99ccc3-8259-4cf2-b063-f99020332bd7
          作用： 进入货物修改页面，信息回显  1、生产货物的厂家  2、货物信息
          参数： 货物id
         */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id){
        //1、查询生产货物的工厂
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物").andCompanyIdEqualTo(getLoginUserCompanyId());
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        //2、货物信息
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);

        return "cargo/product/product-update";
    }

    /*
    url:/cargo/contractProduct/delete.do?
    参数：货物id、购销合同contractId
    作用：删除某个货物
    返回值 : 货物列表
     */
    @RequestMapping("/delete")
    public String delete(String id,String contractId){

        contractProductService.delete(id);

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    /*
    url:/cargo/contractProduct/toImport.do?contractId=79606e2e-e34b-4c72-9645-762f6bf434fe
    参数：购销合同contractId
    作用：去到上传货物页面
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    /*
    url:/cargo/contractProduct/import.do
    参数：购销合同contractId,上传货物文件file
    作用：货物列表
     */
    @RequestMapping("/import")
    public String importExcel(String contractId,MultipartFile file) throws Exception {
        //1、创建工作簿(上传Excel文件版本.xlsx)
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        //2、得到工作单
        Sheet sheet = workbook.getSheetAt(0);
        //3、得到行数
        int rows = sheet.getPhysicalNumberOfRows();

        //从表的第二行开始读
        for (int i = 1; i < rows; i++) {
            Row row = sheet.getRow(i);
            //一行数据等于一个货物对象
            ContractProduct contractProduct = new ContractProduct();

            //生产厂家
            if (row.getCell(1)!=null){
                String factoryName = row.getCell(1).getStringCellValue();
                contractProduct.setFactoryName(factoryName);
            }

            //货号
            if (row.getCell(2)!=null){
                String productNo = row.getCell(2).getStringCellValue();
                contractProduct.setProductNo(productNo);
            }

            //数量
            if (row.getCell(3)!=null){
                double cnumber = row.getCell(3).getNumericCellValue();
                contractProduct.setCnumber((int) cnumber);
            }
            //包装单位
            if (row.getCell(4)!=null){
                String packingUnit = row.getCell(4).getStringCellValue();
                contractProduct.setPackingUnit(packingUnit);
            }
            //装率
            if (row.getCell(5)!=null){
                double loadingRate = row.getCell(5).getNumericCellValue();
                contractProduct.setLoadingRate(loadingRate+"");
            }
            //箱数
            if (row.getCell(6)!=null){
                double boxNum = row.getCell(6).getNumericCellValue();
                contractProduct.setBoxNum((int) boxNum);
            }
            //单价
            if (row.getCell(7)!=null){
                double price = row.getCell(7).getNumericCellValue();
                contractProduct.setPrice(price);
            }
            //货物描述
            if (row.getCell(8)!=null){
                String productDesc = row.getCell(8).getStringCellValue();
                contractProduct.setProductDesc(productDesc);
            }
            //要求
            if (row.getCell(9)!=null){
                String productRequest = row.getCell(9).getStringCellValue();
                contractProduct.setProductRequest(productRequest);
            }
            //补充信息
            //购销合同id
            contractProduct.setContractId(contractId);
            //工厂id
            Factory factory = factoryService.findByName(contractProduct.getFactoryName(),getLoginUserCompanyId());
            contractProduct.setFactoryId(factory.getId());

            contractProductService.save(contractProduct);
        }

        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }
}
